<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import {
  Card as ACard,
  Descriptions as ADescriptions,
  Avatar as AAvatar,
  Button as AButton,
  Upload,
  message,
  Modal as AModal,
  Form as AForm,
  Input as AInput,
} from 'ant-design-vue'
import { UserOutlined, EditOutlined } from '@ant-design/icons-vue'
import type { FormInstance, UploadChangeParam, UploadProps } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { uploadAvatar, changePassword } from '@/api/manger'
import type { Rule } from 'ant-design-vue/es/form'

const userStore = useUserStore()
const loading = ref(false)
const modalVisible = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formState = ref({
  userAccount: userStore.userInfo?.userAccount || '',
  username: userStore.userInfo?.username || '',
  phone: userStore.userInfo?.phone || '',
  email: userStore.userInfo?.email || '',
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 上传相关
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
  }
  return isJpgOrPng && isLt2M
}

const handleChange = async (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }

  if (info.file.status === 'done') {
    const { response } = info.file
    if (response.code === 200) {
      // 更新用户信息中的头像
      if (userStore.userInfo) {
        const updatedUserInfo = {
          ...userStore.userInfo,
          avatar: response.data,
        }
        userStore.setUserInfo(updatedUserInfo)
      }
      message.success('头像上传成功')
    } else {
      message.error('头像上传失败')
    }
    loading.value = false
  } else if (info.file.status === 'error') {
    loading.value = false
    message.error('头像上传失败')
  }
}

const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadAvatar(file)
    onSuccess(res.data)
  } catch (error) {
    onError(error)
  }
}

// 修改密码相关
const rules: Record<string, Rule[]> = {
  currentPassword: [
    {
      required: true,
      message: '请输入当前密码',
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur',
    },
    {
      min: 8,
      message: '密码长度不能小于8位',
      trigger: 'blur',
    },
    {
      validator(_: unknown, value: string) {
        if (!value) return Promise.resolve()
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
        return regex.test(value)
          ? Promise.resolve()
          : Promise.reject('密码必须包含大小写字母和数字')
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur',
    },
    {
      validator(_: unknown, value: string) {
        if (!value) return Promise.resolve()
        return value === formState.value.newPassword
          ? Promise.resolve()
          : Promise.reject('两次输入的密码不一致')
      },
      trigger: 'blur',
    },
  ],
}

const handleChangePassword = () => {
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    loading.value = true
    await formRef.value?.validate(['currentPassword', 'newPassword', 'confirmPassword'])

    if (!userStore.userInfo?.id) {
      message.error('用户信息异常')
      return
    }

    const res = await changePassword({
      id: userStore.userInfo.id,
      currentPassword: formState.value.currentPassword,
      newPassword: formState.value.newPassword,
    })

    if (res.data.code === 200) {
      message.success('密码修改成功')
      modalVisible.value = false
      // 清空表单
      formState.value.currentPassword = ''
      formState.value.newPassword = ''
      formState.value.confirmPassword = ''
      // 重置表单验证状态
      formRef.value?.resetFields()
    } else {
      message.error(res.data.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    message.error('修改密码失败')
  } finally {
    loading.value = false
  }
}

// 添加取消处理函数
const handleModalCancel = () => {
  modalVisible.value = false
  // 清空表单
  formState.value.currentPassword = ''
  formState.value.newPassword = ''
  formState.value.confirmPassword = ''
  // 重置表单验证状态
  formRef.value?.resetFields()
}
</script>

<template>
  <div class="personal-page">
    <a-card class="user-card">
      <div class="user-header">
        <div class="avatar-wrapper">
          <a-upload
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :custom-request="customRequest"
            @change="handleChange"
          >
            <div class="avatar-container">
              <a-avatar
                :src="userStore.userInfo?.avatar ?? undefined"
                :icon="!userStore.userInfo?.avatar && h(UserOutlined)"
                :size="120"
                class="user-avatar"
              />
              <div class="avatar-mask">
                <EditOutlined />
                <span>更换头像</span>
              </div>
            </div>
          </a-upload>
        </div>
        <div class="user-info">
          <h2>{{ userStore.userInfo?.username || userStore.userInfo?.userAccount }}</h2>
          <p class="role-tag">{{ userStore.userInfo?.userRole === 0 ? '管理员' : '普通用户' }}</p>
        </div>
      </div>

      <a-descriptions title="基本信息" bordered :column="2" class="info-descriptions">
        <a-descriptions-item label="账号">{{
          userStore.userInfo?.userAccount
        }}</a-descriptions-item>
        <a-descriptions-item label="用户名">{{ userStore.userInfo?.username }}</a-descriptions-item>
        <a-descriptions-item label="手机号">{{ userStore.userInfo?.phone }}</a-descriptions-item>
        <a-descriptions-item label="邮箱">{{ userStore.userInfo?.email }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{
            userStore.userInfo?.createTime
              ? new Date(userStore.userInfo.createTime).toLocaleString()
              : '-'
          }}
        </a-descriptions-item>
        <a-descriptions-item label="账号状态">{{
          userStore.userInfo?.userStatus === 0 ? '启用' : '禁用'
        }}</a-descriptions-item>
      </a-descriptions>

      <div class="action-buttons">
        <a-button type="primary" @click="handleChangePassword">修改密码</a-button>
      </div>
    </a-card>

    <!-- 修改密码弹窗 -->
    <a-modal
      title="修改密码"
      v-model:visible="modalVisible"
      :confirmLoading="loading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :maskClosable="false"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="currentPassword" label="当前密码">
          <a-input-password
            v-model:value="formState.currentPassword"
            placeholder="请输入当前密码"
          />
        </a-form-item>
        <a-form-item name="newPassword" label="新密码">
          <a-input-password v-model:value="formState.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item name="confirmPassword" label="确认新密码">
          <a-input-password
            v-model:value="formState.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.personal-page {
  padding: 0;
}

.user-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.user-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.avatar-wrapper {
  position: relative;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
}

.user-avatar {
  border: 2px solid #f0f0f0;
  transition: all 0.3s;
}

.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  opacity: 0;
  transition: all 0.3s;
}

.avatar-mask span {
  margin-top: 8px;
  font-size: 14px;
}

.avatar-container:hover .avatar-mask {
  opacity: 1;
}

.user-info {
  flex: 1;
}

.user-info h2 {
  margin: 0 0 8px;
  font-size: 24px;
  line-height: 32px;
}

.role-tag {
  display: inline-block;
  padding: 2px 8px;
  color: #1890ff;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  font-size: 12px;
}

.info-descriptions {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-descriptions-bordered .ant-descriptions-item-label) {
  background-color: #fafafa;
  width: 120px;
}

:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-input-password) {
  border-radius: 6px;
}

:deep(.ant-btn) {
  border-radius: 6px;
  height: 36px;
  padding: 0 24px;
}
</style>
